<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Cache;
//require_once './sdk/WxpayAPI/lib/WxSend.Api.php';
class AutomaticRfuse extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('AutomaticRfuse')
            ->setDescription('the AutomaticRfuse command');
    }

    protected function execute(Input $input, Output $output)
    {
        file_put_contents('/tmp/refuse_error.txt',1234, FILE_APPEND);
        try {
//            // 指令输出
////    	$output->writeln('automaticdelivery');
//            // 获取自动收货时间
            $time = Db::table('eb_config')->where('name', 'automatic_refuse')->value('value');
            if ($time === null) exit;
            $times = $time * 60;
            // 自动收货(系统评价)
//            $map = '`a.is_pay` = 0';
            $page = 1;
            $limit = 1000;
            while (true) {
                $ids = Db::table('order')->where('status', 0)->where('is_pay', 0)->field('id,order_no,create_time,num,goods_id')->page($page, $limit)->select()->toArray();
                if (!$ids) break;
                foreach ($ids as $key => $value) {
                    $a = $value['create_time'] + $times;//超时订单
                    if (time() >= $a) {
//                        file_put_contents('/tmp/refuse_stock1.txt', json_encode($value['order_no']), FILE_APPEND);
                        $rtn = Db::table('order')->where('order_no', $value['order_no'])->update(['status' => -4]);
//                        file_put_contents('/tmp/refuse_stock2.txt', $rtn, FILE_APPEND);
                        if ($rtn==0) break;
                        $red = Db::table('order_status')->insertGetId([
                            'oid' => $value['id'],
                            'change_message' => '订单已被系统默认取消，库存已还原配置',
                            'name' => '生鲜系统',
                            'phone' => '15583730896',
                            'role_type' => '系统管理员',
                            'create_time' => time(),
                        ]);
                        $red = Db::execute("update goods  set stock=stock+{$value['num']},ice_stock = ice_stock-{$value['num']}  where id={$value['goods_id']}");
                        if ($red == false) {
                            break;
                            file_put_contents('/tmp/refuse_stock.txt', $red, FILE_APPEND);
                        }
                        $page++;
                    } else {
                        break;
                    }
                }
                //if (!$rtn) break;
                $page++;
            }
        } catch (\Exception $e) {
//            var_dump($e->getMessage());
            file_put_contents('/tmp/refuse_error.txt',$e->getMessage(), FILE_APPEND);
        }
    }
}
